package com.atguigu.day02;

import com.atguigu.util.IntSource;
import com.atguigu.util.IntStatistic;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @description :
 * @autor :lyh
 */
public class Example9 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntSource())
                .map(new MapFunction<Integer, IntStatistic>() {
                    @Override
                    public IntStatistic map(Integer in) throws Exception {
                        return new IntStatistic(in, in, 1, in, in);
                    }
                })
                .keyBy(new KeySelector<IntStatistic, String>() {
                    @Override
                    public String getKey(IntStatistic value) throws Exception {
                        return "int";
                    }
                })
                .reduce(new ReduceFunction<IntStatistic>() {
                    @Override
                    public IntStatistic reduce(IntStatistic acc, IntStatistic in) throws Exception {
                        return new IntStatistic(
                                Math.max(acc.max, in.max),
                                Math.min(acc.min, in.min),
                                acc.count + in.count,
                                acc.sum + in.sum,
                                (acc.sum + in.sum) / (acc.count + in.count)

                        );
                    }
                })
                .print();

        env.execute();


    }
}
